package com.sand.service.Imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sand.dao.IBaseDao;
import com.sand.entity.*;
import com.sand.service.IHouseService;
import com.sand.util.FileUpLoad;
import com.sand.util.PageModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@NoArgsConstructor
@Data
@Service(value = "houseService")
public class HouseServiceImp implements IHouseService {
/**
 *
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/12/1/001 9:11
 */
    //Dao层接口
    @Resource(name = "baseDao")
    private IBaseDao baseDao;

    //根据房产id查询房产信息
    @Override
    public HashMap<String, Object> queryHouseById(int id) {
        List<HashMap<String, Object>> list = baseDao.queryObject("select new Map(t1.rid as rid,t1.userId as userId,t1.buildingType as buildingType," +
                "t1.communityId as communityId,t1.constructionArea as constructionArea,t1.rentalType as rentalType,t1.paymentMethod as paymentMethod," +
                "t1.renovationCondition as renovationCondition,t1.houseType as houseType,t1.floorSituation as floorSituation," +
                "t1.towards as towards,t1.housingConfiguration as housingConfiguration,t1.houseDescribe as houseDescribe," +
                "t1.createTime as createTime,t1.price as price,t2.communityName as communityName,t2.communityAddress as communityAddress," +
                "t5.name as cityName,t5.parentId as parentId,t3.housePicture as housePicture,t4.browseNumber as browseNumber," +
                "t4.collectionNumber as collectionNumber,t4.status as status,t4.auditStatus as auditStatus) " +
                "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                "inner join CityEntity t5 on t2.cityId=t5.rid " +
                "inner join HouseattachmentEntity t3 on t1.rid=t3.houseId " +
                "inner join HouserecordEntity t4 on t1.rid=t4.houseId where t3.isHouse=1 and t1.rid=?0", id);

        HashMap<String, Object> map = list.get(0);
        List<String> list1 = baseDao.queryObject("select t1.name from CityEntity t1 where t1.rid=?0", Integer.parseInt(map.get("parentId").toString()));
        map.put("cityNamePro",list1.get(0));

        //添加浏览量
        List<HouserecordEntity> list2 = baseDao.queryObject("select t2 from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId where t1.rid=?0", id);
        HouserecordEntity houseRecord = list2.get(0);
        houseRecord.setBrowseNumber(houseRecord.getBrowseNumber()+1);
        baseDao.updateObject(houseRecord);

        return map;
    }

    /**
     *查询房东房源信息
     * @param limit
     * @param page
     * @param condition
     * @return
     */
    @Override
    public PageModel<HashMap<String, Object>> queryHouseByUserIdLimit(int limit, int page,String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<>();
        //分页开始的位置
        page = (page-1)*limit;
        //创建查询对象
        DetachedCriteria criteria = DetachedCriteria.forClass(HouseEntity.class);
        if(condition!=null){
            JSONObject obj = JSON.parseObject(condition);
            if (obj.get("userId")!=null) {
                List list = baseDao.queryObject("select t1.rid  from HouseEntity t1 where t1.userId = ?0 ",Integer.parseInt(obj.get("userId").toString()));
                criteria.add(Restrictions.in("rid", list));
                if(obj.get("status")!=null){
                    List list1 = baseDao.queryObject("select t1.houseId  from HouserecordEntity t1 where t1.status=?0 and t1.houseId in (?1) ",obj.get("status"),list);
                    criteria.add(Restrictions.in("rid", list1));
                }
            }
        }

        List<Long> list1 = baseDao.queryObjectCommon(criteria.setProjection(Projections.rowCount()));

        criteria.setProjection(null);

        //rid的集合
        criteria.setProjection(Projections.property("rid"));

        criteria.addOrder(Order.desc("rid"));

        //查询到所有
        List list = baseDao.queryObjectLimit(criteria, page, limit);

        long i=list1.get(0);

        int count= (int) i;

        List<HashMap<String, Object>> list2 = baseDao.queryObject("select new Map(t1.rid as rid,t2.communityName as communityName,t2.communityAddress as communityAddress,t1.userId as userId,t1.buildingType as buildingType," +
                "t1.paymentMethod as paymentMethod,t4.status as status," +
                "t1.houseType as houseType,t1.renovationCondition as renovationCondition,t1.createTime as createTime," +
                "t1.towards as towards,t1.housingConfiguration as housingConfiguration,t5.name as name," +
                "t4.auditStatus as auditStatus,t3.housePicture as housePicture,t6.userId as userId) " +
                "from HouseEntity t1 inner join OrdertableEntity t6 on t1.rid=t6.houseId " +
                "inner join ContractEntity t7 on t6.rid=t7.orderId " +
                "inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                "inner join CityEntity t5 on t2.cityId=t5.rid " +
                "inner join HouseattachmentEntity t3 on t1.rid=t3.houseId " +
                "inner join HouserecordEntity t4 on t1.rid=t4.houseId " +
                "where t7.status in (-1,0) and t3.isHouse=0 and t1.rid in(?0) group by t1.rid", list);


        pm.setList(list2);
        pm.setPageNo(page);
        pm.setPageSize(limit);
        pm.setPagecount(count);

        return pm;
    }
    //根据房产id查询房屋图片
    @Override
    public List queryHouseImgs(int id) {
        List<HouseattachmentEntity> list = baseDao.queryObject("from HouseattachmentEntity t where t.isHouse=0 and t.houseId=?0", id);
        return list;
    }
    //根据市id查询条件
    @Override
    public HashMap<String, Object> queryOptionById(int id) {

        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Integer> objList = new ArrayList<>();
        //查询条件
        //查询出当前市下的有房源的区
        List<CityEntity> cityList = baseDao.queryObject("select t1 " +
                "from CityEntity t1 inner join CommunityEntity t2 on t1.rid=t2.cityId " +
                "inner join HouseEntity t3 on t2.rid=t3.communityId " +
                "inner join HouserecordEntity t4 on t3.rid=t4.houseId " +
                "where t4.auditStatus='审核通过' and t4.status='未出租' and t1.parentId=?0 group by t1.rid", id);
        map.put("cityList",cityList);
        for (CityEntity city : cityList) {
            objList.add(city.getRid());
        }
        //查询租赁方式
        List cityList2 = baseDao.queryObject("select t1.rentalType " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) group by t1.rentalType", objList);
        map.put("rentalTypeList",cityList2);
        //查询价位
        List cityList3 = baseDao.queryObject("select t1.price " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) order by t1.price asc", objList);
        map.put("priceList",cityList3);
        //查询房源类型
        List cityList4 = baseDao.queryObject("select t1.buildingType " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) group by t1.buildingType", objList);
        map.put("buildingTypeList",cityList4);
        //查询房源户型
        List cityList5 = baseDao.queryObject("select t1.houseType " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) group by t1.houseType", objList);
        map.put("houseTypeList",cityList5);
        //查询房源朝向
        List cityList6 = baseDao.queryObject("select t1.towards " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) group by t1.towards", objList);
        map.put("towardsList",cityList6);
        //查询房源装修
        List cityList7 = baseDao.queryObject("select t1.renovationCondition " +
                "from HouseEntity t1 inner join HouserecordEntity t2 on t1.rid=t2.houseId " +
                "inner join CommunityEntity t3 on t1.communityId=t3.rid " +
                "inner join CityEntity t4 on t3.cityId=t4.rid " +
                "where t2.auditStatus='审核通过' and t2.status='未出租' and t4.rid in (?0) group by t1.renovationCondition", objList);
        map.put("renovationConditionList",cityList7);
        return map;
    }

    //分页查询房源
    @Override
    public PageModel<HashMap<String, Object>> queryHouseLimit(int limit, int page, int showWi, String condition) {
        PageModel<HashMap<String, Object>> pm = new PageModel<HashMap<String, Object>>();
        //计算开始位置
        int begin=(page-1)*limit;
        //创建查询对象
        DetachedCriteria dc = DetachedCriteria.forClass(HouseEntity.class);
        switch (showWi){
            case 1:
                //添加模糊查询条件
                if(condition!=null){
                    JSONObject obj = JSON.parseObject(condition);

                    if(obj.get("userName")!=null){
                        List list = baseDao.queryObject("select t.userId from UserdetailsEntity t where t.name like '%"+obj.get("userName").toString()+"%'");
                        dc.add(Restrictions.in("userId",list));
                    }
                    if(obj.get("comName")!=null){
                        List list = baseDao.queryObject("select t.rid from CommunityEntity t where t.communityName like '%"+obj.get("comName").toString()+"%'");
                        dc.add(Restrictions.in("communityId",list));
                    }
                    if(obj.get("status")!=null && !"".equals(obj.get("status"))){
                        List list = baseDao.queryObject("select t.rid from HouserecordEntity t where t.status=?0",obj.get("status").toString());
                        dc.add(Restrictions.in("rid",list));
                    }
                }
                List<Long> list1 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
                dc.setProjection(null);
                dc.setProjection(Projections.property("rid"));
                dc.addOrder(Order.desc("rid"));
                List list = baseDao.queryObjectLimit(dc, begin, limit);
                long i=list1.get(0);
                int count= (int) i;

                List<HashMap<String, Object>> list2 = baseDao.queryObject(" select new Map(" +
                        "t4.name as userName,t2.communityName as comName,t1.rid as rid,t1.buildingType as buildType," +
                        "t1.price as price,t1.createTime as createTime,t3.auditStatus as auditStatus,t3.status as status,t5.name as cityName)" +
                        " from UserdetailsEntity t4, " +
                        "HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                        "inner join CityEntity t5 on t2.cityId=t5.rid " +
                        "inner join HouserecordEntity t3 on t1.rid=t3.houseId " +
                        "where t1.userId=t4.userId and t1.rid in (?0)", list);

                pm.setList(list2);
                pm.setPageNo(page);
                pm.setPageSize(limit);
                pm.setPagecount(count);
                break;
            case 2:
                if(condition!=null && !"".equals(condition)){
                    JSONObject obj = JSON.parseObject(condition);
                    if(obj.get("cityId")!=null && !"".equals(obj.get("cityId"))){
                        List ridList1 = baseDao.queryObject("select t1.rid " +
                                "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                                "inner join CityEntity t3 on t2.cityId=t3.rid " +
                                "inner join HouserecordEntity t4 on t1.rid=t4.houseId " +
                                "where t4.auditStatus='审核通过' and t4.status='未出租' " +
                                "and t3.parentId=?0",Integer.parseInt(obj.get("cityId").toString()));
                        dc.add(Restrictions.in("rid",ridList1));
                        if(obj.get("browseNumber")!=null){
                            DetachedCriteria dc2 = DetachedCriteria.forClass(HouserecordEntity.class);
                            dc2.add(Restrictions.in("houseId",ridList1));
                            dc2.setProjection(Projections.property("houseId"));
                            dc2.addOrder(Order.desc("browseNumber"));
                            ridList1 = baseDao.queryObjectLimit(dc2, begin, limit);
                        }
                    }
                }

                dc.setProjection(Projections.property("rid"));
                dc.addOrder(Order.desc("rid"));
                List ridList2 = baseDao.queryObjectLimit(dc, begin, limit);

                List<HashMap<String, Object>> ridLis3 = baseDao.queryObject(" select new Map(" +
                        "t1.rid as rid,t1.houseType as houseType,t1.towards as towards,t1.paymentMethod as paymentMethod," +
                        "t1.price as price,t1.constructionArea as constructionArea,t1.renovationCondition as renovationCondition," +
                        "t1.rentalType as rentalType,t3.name as CityName,t2.communityName as communityName," +
                        "t4.housePicture as housePicture) " +
                        "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                        "inner join CityEntity t3 on t2.cityId=t3.rid " +
                        "inner join HouseattachmentEntity t4 on t1.rid=t4.houseId " +
                        "where t4.isHouse=0 and t1.rid in (?0) group by t1.rid", ridList2);
                pm.setList(ridLis3);
                break;
            case 3:
                if(condition!=null){
                    System.out.println(condition);
                    JSONObject obj = JSON.parseObject(condition);
                    //添加模糊查询条件
                    List cidList = baseDao.queryObject("select t1.rid from CityEntity t1 " +
                                "where t1.parentId=?0",Integer.parseInt(obj.get("cityId").toString()));
                    //添加区县条件
                    if(obj.get("cId")!=null){
                        List comList = baseDao.queryObject("select t1.rid " +
                                "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                                "inner join CityEntity t3 on t2.cityId=t3.rid " +
                                "inner join HouserecordEntity t4 on t1.rid=t4.houseId " +
                                "where t4.auditStatus='审核通过' and t4.status='未出租' " +
                                "and t3.rid=?0",Integer.parseInt(obj.get("cId").toString()));
                        dc.add(Restrictions.in("rid",comList));
                    }else{
                        List comList = baseDao.queryObject("select t1.rid " +
                                "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                                "inner join CityEntity t3 on t2.cityId=t3.rid " +
                                "inner join HouserecordEntity t4 on t1.rid=t4.houseId " +
                                "where t4.auditStatus='审核通过' and t4.status='未出租' " +
                                "and t3.rid in (?0)",cidList);
                        dc.add(Restrictions.in("rid",comList));
                    }
                    //添加租赁方式条件
                    if(obj.get("rentalType")!=null){
                        dc.add(Restrictions.eq("rentalType",obj.get("rentalType").toString()));
                    }
                    //添加价位条件
                    if(obj.get("price")!=null){
                        String str = obj.get("price").toString();
                        String[] split = str.split("-");
                        dc.add(Restrictions.gt("price",Long.parseLong(split[0])));
                        dc.add(Restrictions.lt( "price",Long.parseLong(split[1])));
                    }
                    //添加房型条件
                    if(obj.get("buildingType")!=null){
                        dc.add(Restrictions.eq("buildingType",obj.get("buildingType").toString()));
                    }
                    //添加户型条件
                    if(obj.get("houseType")!=null){
                        dc.add(Restrictions.eq("houseType",obj.get("houseType").toString()));
                    }
                    //添加朝向条件
                    if(obj.get("towards")!=null){
                        dc.add(Restrictions.eq("towards",obj.get("towards").toString()));
                    }
                    //添加装修条件
                    if(obj.get("renovationCondition")!=null){
                        dc.add(Restrictions.eq("renovationCondition",obj.get("renovationCondition").toString()));
                    }
                }
                List<Long> comList3 = baseDao.queryObjectCommon(dc.setProjection(Projections.rowCount()));
                dc.setProjection(null);
                dc.setProjection(Projections.property("rid"));
                List comList = baseDao.queryObjectLimit(dc, begin, limit);
                long j=comList3.get(0);
                int count2= (int) j;
                List<HashMap<String, Object>> comList2 = baseDao.queryObject(" select new Map(" +
                        "t1.rid as rid,t1.houseType as houseType,t1.towards as towards,t1.paymentMethod as paymentMethod," +
                        "t1.price as price,t1.constructionArea as constructionArea,t1.renovationCondition as renovationCondition," +
                        "t1.rentalType as rentalType,t3.name as CityName,t2.communityName as communityName," +
                        "t4.housePicture as housePicture) " +
                        "from HouseEntity t1 inner join CommunityEntity t2 on t1.communityId=t2.rid " +
                        "inner join CityEntity t3 on t2.cityId=t3.rid " +
                        "inner join HouseattachmentEntity t4 on t1.rid=t4.houseId " +
                        "where t4.isHouse=0 and t1.rid in (?0) group by t1.rid", comList);
                pm.setList(comList2);
                pm.setPageNo(page);
                pm.setPageSize(limit);
                pm.setPagecount(count2);
                break;
        }

        return pm;
    }

    @Override
    public boolean addHouse(MultipartFile file, MultipartFile[] files, String data, HttpServletRequest request) {
        //创建时间
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());

        if(data!=null){
            try {
                HouseEntity house = JSON.parseObject(data, HouseEntity.class);
                //将用户设置为房东
                List<UserinfoEntity> list = baseDao.queryObject("from UserinfoEntity t1 where t1.rid=?0", house.getUserId());
                UserinfoEntity user = list.get(0);
                user.setIsHouse(1);
                baseDao.updateObject(user);
                //添加房源
                house.setCreateTime(timestamp);
                boolean bln = baseDao.addObject(house);
                //上传文件
                String name = FileUpLoad.upFile(file, request);
                List<String> names = FileUpLoad.upFiles(files, request);
                //添加记录信息
                HouserecordEntity houser = new HouserecordEntity();
                houser.setHouseId(house.getRid());
                houser.setBrowseNumber(0l);
                houser.setCollectionNumber(0l);
                houser.setStatus("未出租");
                houser.setAuditStatus("未审核");
                baseDao.addObject(houser);
                //添加图片信息
                HouseattachmentEntity housea = new HouseattachmentEntity();
                housea.setHouseId(house.getRid());
                housea.setHousePicture(name);
                housea.setIsHouse(1);
                baseDao.addObject(housea);
                //添加室内图
                if(names!=null && names.size()>0){
                    for (String s : names) {
                        HouseattachmentEntity houseas = new HouseattachmentEntity();
                        houseas.setHouseId(house.getRid());
                        houseas.setHousePicture(s);
                        houseas.setIsHouse(0);
                        baseDao.addObject(houseas);
                    }
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean updateHouse(String data) {
        return false;
    }

    @Override
    public boolean delHouse(int rid) {
        HouseEntity house = new HouseEntity();
        house.setRid(rid);
        boolean bln = baseDao.delObject(house);
        if(bln)return true;
        return false;
    }

    @Override
    public boolean updateHouseStatus(int id,int status) {
        List<HouserecordEntity> list = baseDao.queryObject("from HouserecordEntity t1 where t1.houseId=?0", id);
        HouserecordEntity house = list.get(0);
        switch (status){
            case 0:
                house.setAuditStatus("审核未通过");
                break;
            case 1:
                house.setAuditStatus("审核通过");
                break;
        }
        boolean bln = baseDao.updateObject(house);
        if(bln)return true;
        return false;
    }



    //========================lyl======================
    @Override
    public HouseEntity queryHouseData(int hid) {
        List list =  baseDao.queryObject("from HouseEntity where rid=?0",hid);
        if(list!=null&&list.size()>0){
            return (HouseEntity) list.get(0);
        }

        return null;
    }
}
